/**
 *  Copyright 23.07.2012 oliver.keusemann@googlemail.com
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package de.xelerity.geolessi.srv.impl.mixed;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.util.Properties;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import de.xelerity.geolessi.preferences.Preferences;
import de.xelerity.geolessi.srv.mixed.WSCallerI;

public class WSCallerGoogleAppEngine implements WSCallerI {
	private String PROXYHOST = "";
	private int PROXYPORT = 0; /* 8080 */

	private Log log = LogFactory.getLog(WSCallerGoogleAppEngine.class);

	public WSCallerGoogleAppEngine(String proxy, int proxyport) {
		PROXYHOST = proxy;
		PROXYPORT = proxyport;
	}

	public WSCallerGoogleAppEngine() {
	}

	public byte[] call(String URL) throws Exception {

		URL url = new URL(URL);
		HttpURLConnection connection = null;

		if (PROXYHOST != null && PROXYHOST.trim().length() > 0) {
			Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(PROXYHOST, PROXYPORT));
			Properties systemProperties = System.getProperties();
			systemProperties.setProperty("http.proxyHost", PROXYHOST);
			systemProperties.setProperty("http.proxyPort", PROXYPORT + "");
			systemProperties.setProperty("https.proxyHost", PROXYHOST);
			systemProperties.setProperty("https.proxyPort", PROXYPORT + "");

			connection = (HttpURLConnection) url.openConnection(proxy);

		} else {
			connection = (HttpURLConnection) url.openConnection();
		}

		connection.setDoOutput(true);
		connection.setDoInput(true);
		connection.setRequestMethod(Preferences.RequestMethod);
		connection.setInstanceFollowRedirects(true);

		// OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
		// writer.write("message=" + message);
		// writer.close();

		if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {

			InputStream in = connection.getInputStream();
			int contentLength = connection.getContentLength();

			ByteArrayOutputStream tmpOut;
			if (contentLength != -1) {
				tmpOut = new ByteArrayOutputStream(contentLength);
			} else {
				tmpOut = new ByteArrayOutputStream(12384);
			}

			byte[] buf = new byte[512];
			while (true) {
				int len = in.read(buf);
				if (len == -1) {
					break;
				}
				tmpOut.write(buf, 0, len);
			}
			tmpOut.flush();
			in.close();
			tmpOut.close();

			return tmpOut.toByteArray();

		} else {
			log.error("Connection Response != OK, but " + connection.getResponseCode());
			throw new Exception("Connection Response != OK, but " + connection.getResponseCode());
		}

	}

	@Override
	public void addProperty(String Key, String Value) {

		if (Key != null && Key.equalsIgnoreCase("PROXYHOST")) {
			PROXYHOST = (Value == null ? "" : Value.trim());
		}
		if (Key != null && Key.equalsIgnoreCase("PROXYPORT")) {
			PROXYPORT = Integer.parseInt((Value == null ? "8080" : Value.trim()));
		}

	}

	public static void main(String[] args) {

		WSCallerGoogleAppEngine wsCallerGoogleAppEngine = new WSCallerGoogleAppEngine();

		try {
			byte[] call = wsCallerGoogleAppEngine.call("D");
			System.out.println(new String(call));

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
